package com.cdwh.joylife.net;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.socks.library.KLog;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.converter.scalars.ScalarsConverterFactory;

/**
 * Created by Administrator on 2016/12/5.
 */
public class RetrofitHelper {
    private static Retrofit retrofit;

    private RetrofitHelper() {
    }

    public static void init(final NetProvider provider) {
        //gson converter
        final Gson gson = new GsonBuilder()
                .setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")
                .serializeNulls()
                .setLenient()
                .create();
        //cache
//        File cacheFile = new File(ACache.getCacheFile(), NAME_CACHE_PATH);
//        Cache cache = new Cache(cacheFile, MAX_SIZE_CACHE);

        Interceptor interceptor = new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {

                Request original = chain.request();
                HttpUrl originalHttpUrl = original.url();
                HttpUrl url = originalHttpUrl.newBuilder()
//                        .addQueryParameter("token", SPUtils.getToken())
//                        .addQueryParameter("token", "f0813963cbd8478e9d9858ad5c98867b")
                        .build();
                Request.Builder builder = chain.request().newBuilder().url(url);
                Map<String, String> headers = provider.getHeaders();
                if (headers != null && headers.size() != 0) {
                    for (Map.Entry<String, String> entry : headers.entrySet()) {
                        builder.addHeader(entry.getKey(), entry.getValue());
//                        account-token
//                        account-token
                        KLog.e("header:"+entry.getKey()+"------"+entry.getValue());
                    }
                }
                Request request = builder.build();
                return chain.proceed(request);
            }
        };
        HttpLoggingInterceptor logInterceptor = new HttpLoggingInterceptor(new HttpLogger());
        logInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        //client,//设置超时时间
        final OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(provider.getTimeout(), TimeUnit.SECONDS)
                .writeTimeout(provider.getTimeout(), TimeUnit.SECONDS)
                .readTimeout(provider.getTimeout(), TimeUnit.SECONDS)
//                .cache(cache)
                .addInterceptor(interceptor)
                .addInterceptor(logInterceptor)
                .build();
        retrofit = new Retrofit.Builder()
                .baseUrl(provider.getBaseUrl())
                .addConverterFactory(ScalarsConverterFactory.create())
                .addConverterFactory(GsonConverterFactory.create(gson))
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .client(client)
                .build();
    }

    private static class HttpLogger implements HttpLoggingInterceptor.Logger {
        @Override
        public void log(String message) {

            if (message.contains("http:")) {
                KLog.e("Url", message);
            }
            if (message.startsWith("{")) {
                KLog.json(message);
                KLog.e("data:", message);
            }
        }
    }

    public static Retrofit getRetrofit() {
        return retrofit;
    }

}